//
//  LoginViewController.swift
//  APH
//
//  Created by Rdxer on 2017/12/7.
//  Copyright © 2017年 Rdxer. All rights reserved.
//

import UIKit
import SnapKit
import XXAutoLayout
import Spring
import FastComponent
import RxSwift
import RxCocoa
import XXLogger
import Moya
import Device

class LoginViewController: XXBaseViewController {
    
    let userAPI:MoyaProvider<UserApi> = APIProviderManager.makeProvider()
    
    // 图
    var topImageView:UIImageView!
    var iconShadowImageView:SpringImageView!
    var dividerImageView:UIImageView!
    var dividerBackImageView:UIImageView!
    
    // 登陆相关
    var userNameTextField:UITextField!
    var passwordTextField:UITextField!
    var loginButton:UIButton!
    
    // copyright
    var copyrightLabel:UILabel!
    
    override var preferredStatusBarStyle: UIStatusBarStyle{
        return .lightContent
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
//        CheckUpdateManager.shared.checkIfNeed()
        
        prepareBackView()
        prepareLoginView()
        prepareEvent()
        
        prepareAddListenKeyboard()
        
        #if DEBUG
//            switch AppConfig.current {
//            case .debug(_):
//                userNameTextField.text = "yaofang"
//                passwordTextField.text = "1"
//            default:break
//            }
        #endif
        
    }

    deinit {
        removeListenKeyboard()
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        self.view.endEditing(true)
    }
    
    @objc func loginButtonClick(){
    // ^[a-z0-9_-]{6,20}$
        
        guard let userName = userNameTextField.text?.trim.nilOrNotEmptyString,
            userName =~ "^.*?$" else{
            HUD.showInfo(withStatus: "用户名称格式不正确..")
            return;
        }
        
        guard let password = passwordTextField.text?.trim.nilOrNotEmptyString,
            password =~ "^.*?$"  else {
            HUD.showInfo(withStatus: "密码格式不正确..")
            return;
        }
        
        HUD.show()
        
        // 登陆
//        userAPI.rx.request(.Login(userName: userName, password: password, validateCode: nil))
//        .filterWhenNeedRefreshToken(target: self, sel: #selector(loginButtonClick))
//        .mapModelListWithDataValue(AuthData.self)
//        .subscribe(onSuccess: { (resp) in
//            guard let loginData = resp.first as? LoginData else{
//                HUD.showError(withStatus: "用户名或者密码错误")
//                return
//            }
//            
//            AccountManager.shared.login(loginData: loginData)
//            CheckAccountManager.shared.save(loginRequest: LoginRequest.init().then({
//                $0.USERNAME = userName
//                $0.PASSWORD = password
//            }))
//            
//            HUD.showSuccess(withStatus: "登录成功.")
//            
//            AppRoutes.shared.switchToLauchAutoChooseVC()
//            
//        }){ err in
//            showErrorHUD(err)
//        }
//        .disposed(by: self)
    }
}

extension LoginViewController {

    func prepareEvent(){
        // 键盘上 next
        userNameTextField.rx
            .controlEvent(.editingDidEndOnExit)
            .map({true})
            .bind(to: passwordTextField.rx.isFirstResponder())
            .disposed(by: dispose)
        
        // 键盘上 go
        passwordTextField.rx.controlEvent(.editingDidEndOnExit)
            .map({[weak self] in return self!.loginButton.isEnabled })
            .filter({return $0})
            .subscribe(onNext: { [weak self](_Bool) in
                self?.loginButton.sendActions(for: .touchUpInside)
            })
            .disposed(by: dispose)
    }
    func prepareBackView(){
        topImageView = UIImageView.init(image: UIImage.init(named: "登录3_01"))
        iconShadowImageView = SpringImageView.init(image: UIImage.init(named: "登录3_03的副本-2"))
        dividerImageView = UIImageView.init(image: UIImage.init(named: "登录3_2"))
        dividerBackImageView = UIImageView.init(image: UIImage.init(named: "登录3_02"))
        
        view.addSubview(topImageView)
        
        view.addSubview(iconShadowImageView)
        
        view.addSubview(dividerBackImageView)
        view.addSubview(dividerImageView)
        topImageView.snp.makeConstraints { (maker) in
            maker.top.left.right.equalToSuperview()
            
            if Device.isPad(){
                maker.height.equalToSuperview()
                    .multipliedBy(0.6)
            }else{
                maker.height.equalTo(900.from1080)
            }
        }
        
        iconShadowImageView.snp.makeConstraints { (maker) in
            maker.center.equalTo(topImageView)
        }
        
        dividerBackImageView.snp.makeConstraints { (maker) in
            maker.left.right.bottom.equalTo(topImageView)
            maker.height.equalTo(135.from1080)
        }
        
        dividerImageView.snp.makeConstraints { (make) in
            make.edges.equalTo(dividerBackImageView)
        }
        
        iconShadowImageView.animation = "fadeInUp"
        iconShadowImageView.curve = "spring"
        iconShadowImageView.duration = 2
        iconShadowImageView.animate()
    }
    
    func prepareLoginView(){
        userNameTextField = UITextField.init()
        passwordTextField = UITextField.init()
        loginButton = UIButton.init(type: UIButtonType.roundedRect)
        copyrightLabel = UILabel.init()
        
        view.addSubview(userNameTextField)
        view.addSubview(passwordTextField)
        view.addSubview(loginButton)
        view.addSubview(copyrightLabel)
        
        // 流程与标准化管理系统
        copyrightLabel.text = "流程与标准化管理系统"
        copyrightLabel.textColor = UIColor.init("aaaaaa")
        copyrightLabel.font = UIFont.systemFont(ofSize: 12)
        
        if Device.isPad() {
            copyrightLabel.snp.makeConstraints({ (make) in
                make.bottom.equalToSuperview()
                    .offset(-23)
                make.centerX.equalToSuperview()
            })
        }else{
            copyrightLabel.xx_AlignInner(with: .bottomCenter, referView: view, size: CGSizeNull(), offset: CGPoint.init(x: 0, y: -70.from1080))
        }
        // login
        loginButton.backgroundColor = UIColor.init("f3202d")
        loginButton.setTitle("登录", for: .normal)
        loginButton.setTitleColor(UIColor.white, for: .normal)
        loginButton.layer.cornerRadius = 44 * 0.5
        loginButton.clipsToBounds = true
        loginButton.addTarget(self, action: #selector(loginButtonClick), for: UIControlEvents.touchUpInside)
        
        if Device.isPad() {
            loginButton.snp.makeConstraints({ (make) in
                make.centerX.equalToSuperview()
                make.bottom.equalTo(copyrightLabel.snp.top)
                    .offset(-60)
                make.size.equalTo(CGSize.init(width: 400, height: 44))
            })
        }else{
            loginButton.xx_AlignVertical(with: .topCenter, referView: copyrightLabel, size: .init(width: 460.from1080, height: 134.from1080), offset: .init(x: 0, y: -180.from1080))
        }
        // textfield
        userNameTextField.textAlignment = .center
        passwordTextField.textAlignment = .center
        
        userNameTextField.placeholder = "用户名"
        passwordTextField.placeholder = "密码"
        
        userNameTextField.autocapitalizationType = .none
        passwordTextField.autocapitalizationType = .none
        
        userNameTextField.returnKeyType = .next
        passwordTextField.returnKeyType = .go
        
        userNameTextField.keyboardType = .asciiCapable
        userNameTextField.autocorrectionType = .no
        
        userNameTextField.xx_Add(dividerColor: UIColor.init("cbcaca")!,dividerWidth:1)
        passwordTextField.xx_Add(dividerColor: UIColor.init("cbcaca")!,dividerWidth:1)
        
        passwordTextField.isSecureTextEntry = true
        
        
        if Device.isPad() {
            
            passwordTextField.snp.makeConstraints { (make) in
                make.width.equalTo(400)
                make.height.equalTo(44)
                make.centerX.equalToSuperview()
                make.bottom.equalTo(loginButton.snp.top)
                    .offset(-44)
            }
            
            userNameTextField.snp.makeConstraints { (make) in
                make.width.equalTo(400)
                make.height.equalTo(44)
                make.centerX.equalToSuperview()
                make.bottom.equalTo(passwordTextField.snp.top)
                    .offset(-44)
            }

            
        }else{
            passwordTextField.snp.makeConstraints { (make) in
                make.width.equalTo(460.from1080)
                make.centerX.equalToSuperview()
                make.bottom.equalTo(loginButton.snp.top)
                    .offset(-140.from1080)
            }
            
            userNameTextField.snp.makeConstraints { (make) in
                make.width.equalTo(460.from1080)
                make.centerX.equalToSuperview()
                make.bottom.equalTo(passwordTextField.snp.top)
                    .offset(-140.from1080)
            }
        }
    }
}

// LoginViewController  prepareAddListenKeyboard
extension LoginViewController{
    func prepareAddListenKeyboard(){
        NotificationCenter.default.addObserver(self, selector: #selector(xx_UIKeyboardWillChangeFrame(notification:)), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
    }
    
    func removeListenKeyboard(){
        NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
    }
    
    @objc func xx_UIKeyboardWillChangeFrame(notification: NSNotification){
        let info = notification.userInfo
        let kbRect = (info?[UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
        var offsetY:CGFloat = 0
        if Device.isPad() {
            offsetY = (CGFloat(0)) + kbRect.origin.y - UIScreen.main.bounds.height
        }else{
            offsetY = (280.from1080) + kbRect.origin.y - UIScreen.main.bounds.height
        }
        let y = XXMathLibrary.absLimit(offsetY, min: -9999, max: 0)
        UIView.animate(withDuration: 0.3) {
            self.view.transform = CGAffineTransform(translationX: 0, y: y)
        }
    }

}

